/**
 *
 *  Copyright (c) 2011, AstroDAbis
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without modification,
 *  are permitted provided that the following conditions are met:
 *
 *      * Redistributions of source code must retain the above copyright notice,
 *        this list of conditions and the following disclaimer.
 *      * Redistributions in binary form must reproduce the above copyright notice,
 *        this list of conditions and the following disclaimer in the documentation
 *        and/or other materials provided with the distribution.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 *  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 *  OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
package org.jiscinvolve.astrodabis.galium.ogsadai.activity.server;

import uk.org.ogsadai.config.Key;
import uk.org.ogsadai.config.KeyValueProperties;

import uk.org.ogsadai.activity.MatchedIterativeActivity;
import uk.org.ogsadai.activity.ActivityUserException;
import uk.org.ogsadai.activity.ActivityProcessingException;
import uk.org.ogsadai.activity.ActivityTerminatedException;

import uk.org.ogsadai.activity.extension.ResourceManagerActivity;
import uk.org.ogsadai.activity.extension.ResourceFactoryActivity;
import uk.org.ogsadai.activity.extension.ConfigurableActivity;
import uk.org.ogsadai.activity.extension.SecureActivity;

import uk.org.ogsadai.common.msgs.DAILogger;

import uk.org.ogsadai.activity.io.BlockWriter;
import uk.org.ogsadai.activity.io.PipeClosedException;
import uk.org.ogsadai.activity.io.PipeIOException;
import uk.org.ogsadai.activity.io.PipeTerminatedException;
import uk.org.ogsadai.activity.io.ActivityPipeProcessingException;

import uk.org.ogsadai.activity.io.ActivityInput;
import uk.org.ogsadai.activity.io.TypedActivityInput;
import uk.org.ogsadai.activity.io.TypedOptionalActivityInput;

import uk.org.ogsadai.resource.Resource;
import uk.org.ogsadai.resource.ResourceID;
import uk.org.ogsadai.resource.ResourceState;
import uk.org.ogsadai.resource.ResourceFactory;
import uk.org.ogsadai.resource.ResourceManager;
import uk.org.ogsadai.resource.ResourceTypeException;
import uk.org.ogsadai.resource.ResourceUnknownException;
import uk.org.ogsadai.resource.ResourceIDAlreadyAssignedException;
import uk.org.ogsadai.resource.generic.GenericResource;

import uk.org.ogsadai.exception.DAIClassMissingInterfaceException;

import uk.org.ogsadai.authorization.SecurityContext;

/*
 *
 * Example resource config.
 *  
 *  id=ROEsdssDR7
 *  type=uk.org.ogsadai.DATA_RESOURCE
 *  creationTime=null
 *  terminationTime=null
 *  PROPERTIES
 *  END
 *  CONFIG
 *  dai.astro.tapurl=http://wfaudata.roe.ac.uk/sdssdr7-dsa/TAP
 *  END
 *  ACTIVITIES
 *  uk.org.ogsadai.SQLQuery=aida.SQLQuery
 *  uk.org.ogsadai.ExtractTableSchema=aida.ExtractTableSchema
 *  uk.org.ogsadai.ExtractPhysicalSchemaToXML=aida.ExtractPhysicalSchemaToXML
 *  END
 *  dataResourceClass=uk.org.ogsadai.resource.generic.GenericResource
 *
 */


/**
 * An Activity to create a TAP resource.
 *
 * Based on the example
 * <a href='http://ogsa-dai.sourceforge.net/documentation/ogsadai4.0/ogsadai4.0-gt/DeveloperWriteResourceFactory.html'>resource factory activity</a> 
 * from the OGSA-DAI documentation.
 *
 */ 
public class CreateTapResourceActivity 
    extends MatchedIterativeActivity
    implements ResourceManagerActivity, 
               ResourceFactoryActivity,
               ConfigurableActivity,
               SecureActivity
    {

    /**
     * Our debug logger.
     * 
     */
    private static final DAILogger log = 
        DAILogger.getLogger(CreateTapResourceActivity.class);

    /** 
     * Key into activities configuration file denoting the
     * default template resource ID (<code>dai.template.id</code>).
     *
     */
    public static final Key TEMPLATE_ID_KEY = new Key("dai.template.id");

    /** 
     * The configuration key for the TAP endpoint URL.
     *
     */
    public static final Key TAP_URL_KEY = new Key("dai.astro.tapurl");

    /**
     * Activity input name (<code>resourceId</code>)
     * - ID of the new resource to create (<code>String</code>). 
     *
     */
    public static final String INPUT_RESOURCE_ID = "resourceId";

    /**
     * Activity input name (<code>templateId</code>)
     * - ID of the resource template (<code>String</code>). 
     *
     */
    public static final String INPUT_TEMPLATE_ID = "templateId";

    /**
     * Activity input name (<code>endpoint</code>)
     * - TAP endpoint URL (<code>String</code>). 
     *
     */
    public static final String INPUT_ENDPOINT_URL = "endpoint";

    /**
     * Activity output name (<code>result</code>)
     * - ID of the newly created resource(<code>String</code>). 
     *
     */
    public static final String RESULT = "result";

    /**
     * Result block writer.
     *
     */
    private BlockWriter mResult;
    
    /**
     * OGSA-DAI resource manager.
     *
     */
    private ResourceManager mResourceManager;

    /**
     * OGSA-DAI resource factory utility.
     *
     */
    private ResourceFactory mResourceFactory;

    /**
     * Default template resource ID.
     *
     */
    private ResourceID mTemplateID;

    /**
     * {@inheritDoc}
     *
     */
    public void setResourceManager(ResourceManager resourceManager)
        {
        log.debug("CreateTapResourceActivity.setResourceManager(ResourceManager)");
        mResourceManager = resourceManager;        
        }

    /**
     * {@inheritDoc}
     *
     */
    public void setResourceFactory(ResourceFactory resourceFactory)
        {
        log.debug("CreateTapResourceActivity.setResourceFactory(ResourceFactory)");
        mResourceFactory = resourceFactory;        
        }

    /**
     *
     */
    protected ActivityInput[] getIterationInputs()
        {
        log.debug("CreateTapResourceActivity.getIterationInputs()");
        return new ActivityInput[] {
            new TypedOptionalActivityInput(
                INPUT_RESOURCE_ID,
                String.class
                ),
            new TypedOptionalActivityInput(
                INPUT_TEMPLATE_ID,
                String.class
                ),
            new TypedActivityInput(
                INPUT_ENDPOINT_URL,
                String.class
                )
            };
        }

    /**
     * {@inheritDoc}
     *
     */
    protected void preprocess() 
        throws ActivityUserException,
               ActivityProcessingException, 
               ActivityTerminatedException
        {
        log.debug("CreateTapResourceActivity.preprocess()");
        validateOutput(RESULT);
        mResult = getOutput();
        }

    /**
     * {@inheritDoc}
     *
     */
    protected void processIteration(Object[] iterationData)
        throws ActivityProcessingException, 
               ActivityTerminatedException,
               ActivityUserException
        {
        log.debug("CreateTapResourceActivity.processIteration(Object[])");
        //
        // Get our resource ID.
        ResourceID resourceID;
        if (iterationData[0] != null)
            {
            resourceID = new ResourceID(
                (String)iterationData[0]
                );
            }
        else {
            resourceID = mResourceManager.createUniqueID();
            }

        log.debug("Resource ID [" + resourceID + "]");

        //
        // Get our template ID.
        ResourceID templateID;
        if (iterationData[1] != null)
            {
            templateID = new ResourceID(
                (String)iterationData[1]
                );
            }
        else {
            templateID = mTemplateID;
            }

        log.debug("Template ID [" + templateID + "]");

        //
        // Get our endpoint URL.
        String endpoint = null;
        if (iterationData[2] != null)
            {
            endpoint = (String)iterationData[2];
            }
        else {
            throw new ActivityProcessingException(
                new IllegalArgumentException(
                    "TAP service endpoint is required"
                    )
                );
            }

        log.debug("Endpoint URL [" + endpoint + "]");

        //
        // Try creating our resource.
        try {
            //
            // Create a generic resource from our template.
            GenericResource resource = null;
            try {
                log.debug("Creating resource ...");
                resource = createResource(templateID);
                } 
            catch (ResourceUnknownException ouch)
                {
                // If we couldn't find the template.
                if (iterationData[1] != null)
                    {
                    throw new ActivityUserException(
                        ouch
                        );
                    }
                // Something else.
                else {
                    throw ouch;
                    }
                }
            //
            // Get the resource state.
            log.debug("Getting state ...");
            ResourceState state = resource.getState() ;
            //
            // Make the resource transient.
            log.debug("Setting transient ...");
            state.setTransient(true);
            //
            // Set the endpoint URL.
            log.debug("Setting endpoint ...");
            KeyValueProperties settings = state.getConfiguration();
            settings.put(
                TAP_URL_KEY,
                endpoint
                );
            //
            // Add the new resource to the OGSA-DAI resource manager.
            log.debug("Adding resource ...");
            mResourceFactory.addResource(
                resourceID,
                resource
                );
            //
            // Output the resource ID.
            log.debug("Writing result ...");
            mResult.write(
                resource.getResourceID().toString()
                );
            }

        catch (PipeClosedException e)
            {
            // No more input wanted.
            iterativeStageComplete();
            }
        catch (PipeTerminatedException e)
            {
            throw new ActivityTerminatedException();
            }
        catch (PipeIOException e)
            {
            throw new ActivityPipeProcessingException(e);
            }
        catch (ResourceIDAlreadyAssignedException e)
            {
            throw new ActivityUserException(e);
            }
        catch (ActivityUserException e)
            {
            throw e;
            }
        catch (Exception e)
            {
            throw new ActivityProcessingException(e);
            }
        }

    /**
     * {@inheritDoc}
     *
     * No post-processing.
     */
    protected void postprocess() 
        throws ActivityUserException,
               ActivityProcessingException, 
               ActivityTerminatedException
        {
        log.debug("CreateTapResourceActivity.postprocess()");
        // No post-processing.
        }  


    /**
     * Create empty resource from the template.
     *
     */
    public GenericResource createResource(ResourceID templateID)
        throws ResourceTypeException,
               ResourceUnknownException,
               DAIClassMissingInterfaceException
        {
        log.debug("CreateTapResourceActivity.createResource(ResourceID)");

        Resource resource = mResourceFactory.createDataResource(templateID);
        if (resource instanceof GenericResource)
            {
            return (GenericResource)resource;
            }
        else {
            throw new DAIClassMissingInterfaceException(
                resource.getClass().getName(),
                GenericResource.class.getName()
                );
            }
        }

    /**
     * Extracts value with key <code>dai.template.id</code> and attempts
     * to parse into a <code>uk.org.ogsadai.resource.ResourceID</code>.
     *
     */
    public void configureActivity(KeyValueProperties properties)
        {
        log.debug("CreateTapResourceActivity.configureActivity(KeyValueProperties)");
        mTemplateID = new ResourceID(
            (String)properties.get(
                TEMPLATE_ID_KEY
                )
            );
        log.debug("Template ID [" + mTemplateID + "]");
        }

    /**
     * {@inheritDoc}
     *
     */
    public void setSecurityContext(SecurityContext context)
        {
        // mSecurityContext = context;
        }

    }
